import { createElement as h } from "./shared/createElement"
import './style.scss'

// 准备 HTML
const root = document.getElementById('root');
const container = h('div', { class: 'container' })
const chart = h('div', { class: 'chart' })
container.append(chart)
root?.append(container)

// 准备数据
const heightUnit = 16
const widthUnit = 24

const array = [10, 6, 5, 7, 3, 4, 1, 2, 8, 9]
chart.style.height = `${Math.max(...array) * 16}px`
const bars = array.map((n, index) =>
  h('div', {
    class: 'bar',
    style: {
      height: `${n * heightUnit}px`,
      transform: `translateX(${index * (widthUnit + 1)}px)`,
    },
    dataset: { index }
  },
    h('span', null, n)
  )
)
chart.append(...bars)

// 添加按钮
const button = h('button', null, '交换')
button.addEventListener('click', async () => {
  for (let i = 0; i + 1 < array.length; i++) {
    await swap(i, i + 1)
  }
})
container.append(button)

// 助手函数
const swap = (a: number, b: number) => {
  return new Promise<void>((resolve, reject) => {
    [array[a], array[b]] = [array[b], array[a]]
    const barA = bars.find(t => t.dataset.index === a.toString())!;
    const barB = bars.find(t => t.dataset.index === b.toString())!;
    barA.classList.add('moving');
    barB.classList.add('moving');
    ;[barA.dataset.index, barB.dataset.index] = [barB.dataset.index, barA.dataset.index];
    ;[barA.style.transform, barB.style.transform] = [barB.style.transform, barA.style.transform]
    barA.addEventListener('transitionend', () => {
      barA.classList.remove('moving');
      barB.classList.remove('moving');
      resolve()
    })
  })
}
export { }